import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { isTaggedTemplateExpression } from 'typescript'
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-smt-detection-page',
  templateUrl: './smt-detection-page.component.html',
  styleUrls: ['./smt-detection-page.css']
})
export class SmtDetectionPageComponent implements OnInit {
  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      checkDate: {
        validators: {
          notEmpty: {
            message: '请选择检验日期'
          },
          date: {
            format: 'YYYY-MM-DD',
            message: '请选择正确的时间,例如2018-01-01'
          }
        }
      },
      productName: {
        validators: {
          notEmpty: {
            message: '请输入产品名称'
          }
        }
      },
      sensor: {
        validators: {
          notEmpty: {
            message: '请输入通道数'
          }
        }
      },
      iotCardType: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择物联卡类型'
          }
        }
      },
      orderNum: {
        validators: {
          notEmpty: {
            message: '请输入订单数量'
          }
        }
      },
      checkNum: {
        validators: {
          notEmpty: {
            message: '请输入检测数量'
          }
        }
      }
    }
  }
  pageFormData: any = {
    checkDate: '', //检验日期
    orderNumber: '', //订单号
    materialCode: '', //物料编码
    productName: '', //产品名称
    sensor: '', //通道数
    iotCardType: '', //物联卡类型
    orderNum: '', //订单数量
    checkNum: '', //检测数量
    badNum: 0, //不良数量
    badInfoList: [] //不良原因列表
  }
  page_title: string = '新增'
  pageType: string = 'new'
  type = 1
  curPage = 0 //页码缓存
  jumpData: any = {}
  badReasonData: any = []
  name: string = ''
  path: string = ''
  editUrl: string = ''
  isAddHostAssembly: boolean = false
  typeList = [
    {
      value: '0000',
      label: '通用卡'
    },
    {
      value: '0001',
      label: '新疆卡'
    },
    {
      value: '0002',
      label: '云南卡'
    }
  ]

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage
      this.pageType = queryParams.pageType
      this.type = queryParams.type
      this.name = queryParams.name
      this.path = queryParams.path
      this.editUrl = queryParams.editUrl
      if (this.name === '主机组装测试') {
        this.isAddHostAssembly = true
      }
      if (common.getCookie('checkedUpdata')) {
        const jumpData = JSON.parse(common.getCookie('checkedUpdata'))
        common.clearCookie('checkedUpdata')
        jumpData.checkDate = jumpData.checkDate.substring(0, 10)
        this.pageFormData = { ...jumpData }
      }
    })
  }
  typeChange(e) {
    $('#purchaseForm').data('bootstrapValidator').resetForm()
  }
  //表单校验
  onSubmit() {
    $('#purchaseForm').bootstrapValidator('validate') //开启验证
    const isValid = $('#purchaseForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.updata()
    }
  }
  //表单数据提交
  updata() {
    const formData = JSON.parse(JSON.stringify(this.pageFormData))
    console.log(formData, 'formData')
    formData.orderNum = parseInt(formData.orderNum)
    formData.checkNum = parseInt(formData.checkNum)
    formData.badNum = parseInt(formData.badNum)

    if (formData.checkNum > formData.orderNum) {
      this.jsonApiService.message('检测数量不能大于订单数量')
      return
    }
    if (formData.badNum > formData.checkNum) {
      this.jsonApiService.message('不良数量不能大于检测数量')
      return
    }
    formData.badInfoList = this.pageFormData.badInfoList.filter(item => item.count > 0)

    if (this.type == 3) {
      formData.badList = formData.badInfoList
    }

    const data = {
      ...formData
    }
    this.jsonApiService.json_http(this.editUrl, data).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.goBack()
      }
    })
  }
  //返回资源列表页
  goBack() {
    this.router.navigate([this.path], { queryParams: { nowPage: this.curPage } })
  }
  ngOnInit() {
    var that = this
    this.initDate().then(() => {
      if (this.pageType === 'updata') {
        this.page_title = '编辑'
      }
      this.getBadReasonData()
    })
  }
  //获取不良原因数据
  getBadReasonData() {
    let data = {
      type: this.type
    }
    this.jsonApiService.http_obj('badReasonConfig/queryBadReasonConfigList.html', data).subscribe(result => {
      if (result.success) {
        const results = JSON.parse(JSON.stringify(result.data))
        results.map(item => {
          item.checked = false
        })
        this.badReasonData = results
      } else {
        this.jsonApiService.message(result.message)
      }
    })
  }

  // 删除输入
  delKey(str) {
    this.pageFormData[str] = ''
  }
  // 打开弹窗
  selectBadReason(modal) {
    if (this.pageType === 'updata' && this.pageFormData.badInfoList.length > 0) {
      this.badReasonData.map(item => {
        this.pageFormData.badInfoList.map(ele => {
          if (item.id === ele.id) {
            item.checked = true
          }
        })
      })
    }
    modal.show()
  }
  // 关闭弹窗
  modalClose(modal) {
    modal.hide()
  }

  //确认选择不良原因
  badReasonSubmit(modal) {
    modal.hide()
    $('#purchaseForm').data('bootstrapValidator').resetForm()
    const filterData = this.badReasonData.filter(item => item.checked)
    const newData: any = this.deepClone(filterData)
    if (this.pageFormData.badInfoList.length > 0) {
      newData.map(ele => {
        ele.count = ''
        this.pageFormData.badInfoList.map(item => {
          if (item.id === ele.id) {
            ele.count = item.count
          }
        })
      })
      this.pageFormData.badInfoList = this.deepClone(newData)
    } else {
      this.pageFormData.badInfoList = newData.map(item => {
        item.count = ''
        return item
      })
    }
    this.getBadReasonTotal()
  }

  //深拷贝浅拷贝
  deepClone(obj) {
    let objClone = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          //判断ojb子元素是否为对象，如果是，递归复制
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key])
          } else {
            //如果不是，简单复制
            objClone[key] = obj[key]
          }
        }
      }
    }
    return objClone
  }

  //关键字检索
  keywordSearch() {
    var key = $('#keywordSearch').val() //取key值
    if (!key) {
      $('.result').each(function () {
        //恢复原始数据
        $(this).replaceWith($(this).html())
      })
      return //key为空则退出
    } else {
      $('.result').each(function () {
        $(this).replaceWith($(this).html())
      })
      //   const regExp = new RegExp(key + '(?!([^<]+)?>)', 'ig') //正则表达式匹配
      const regExp = new RegExp(key + '(?!([^<]+)?>)', 'g') //正则表达式匹配
      $('.item-name').map((index, ele) => {
        const html = $(ele)[0].innerHTML
        const newHtml = html.replace(regExp, "<span class='result' style='background: yellow;'>" + key + '</span>')
        $(ele).html(newHtml)
      }) // 高亮操作
    }
  }

  // 数量减
  reduceNum(item) {
    if (item.count == '' || item.count == 0) {
      item.count = 0
      this.getBadReasonTotal()
      return
    }
    item.count--
    this.getBadReasonTotal()
  }
  // 数量加
  addNum(item) {
    if (item.count === '') {
      item.count = 1
      this.getBadReasonTotal()
      return
    }
    item.count++
    this.getBadReasonTotal()
  }
  // 数量改变
  numChange(value, item) {
    item.count = value
    this.getBadReasonTotal()
  }

  //汇总不良数量
  getBadReasonTotal() {
    $('#purchaseForm').data('bootstrapValidator').resetForm()
    let total = 0
    this.pageFormData.badInfoList.map(item => {
      if (item.count) {
        total += parseInt(item.count)
      }
    })
    this.pageFormData.badNum = total
  }

  //初始化时间
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker1')
            .datetimepicker({
              format: 'yyyy-mm-dd',
              language: 'zh-CN',
              autoclose: true,
              minView: 2
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeDay(date)
              that.pageFormData.checkDate = time
              $('#purchaseForm').data('bootstrapValidator').resetForm()
            })
          resolve()
        })
      })
    })
  }
}
